$(document).ready(function(){
	var numberOfBanners = 15;
	var page = 0;
	var module = 'banner';
	var timeOutTime = 5000;
	
	var selectPriv = 0;
	var insertPriv = 0;
	var updatePriv = 0;
	var deletePRiv = 0;

	initControls();
	
	// this is synchronous function, so it must runs after initControl
	getPrivs();	
	
	shouldCreateNewButton();
	shouldListBanner();
	
	function initControls()
	{
		initBannerTypeSelect();
		initNewBannerDialog();
		initEditBannerDialog();
		initRemoveBannerDialog();
	}
	
	function shouldCreateNewButton()
	{
		$('#newBannerButtonWrapper').remove();		
		if(insertPriv) {
			var newButtonHTML = '<span id="newBannerButtonWrapper" style="padding: 0 0 5px 0;"><input id="newBannerButton" type="button" value="Thêm mới" /></span>';						
			
			// add it to tab content
			$('#topWrapper').append(newButtonHTML);			
			
			// add UI
			$('#newBannerButton').button();
			
			// add new event handler
			$("#newBannerButton").click(function(){
				newBanner();		
			});
		}
	} // end shouldCreateNewButton function
	
	// when select_priv is true, loadBannerType select and listBanenrTableWrapper will show
	function shouldListBanner()
	{
		if(selectPriv) {			
			loadBannerType();
			$('#listBannerTypeSelectWrapper').show();
			$('#listBannerTableWrapper').show();
			loadBanner();
		} else {
			$('#selectPrivReport').show();
		}
		
		// fix bug 'padding' of 'topWrapper'
		if(insertPriv == 0 && selectPriv == 0) {
			$('#topWrapper').remove();
		}
	} // end shouldListBanner functions

	function getPrivs()
	{
		$.ajax({
			url: '/privilege/get-privs',
			data: {module: module},			
			async: false,
			timeout: timeOutTime,
			success: function(json){
				var returnData = $.parseJSON(json);
				var data = returnData.data;
				if(returnData.code == 0) {
					selectPriv = data.SELECT_PRIV;
					insertPriv = data.INSERT_PRIV;
					updatePriv = data.UPDATE_PRIV;
					deletePriv = data.DELETE_PRIV;
				}
			},
			error: function(jqXHR, textStatus, errorThrown) {
				if(textStatus == 'timeout') {					
					getPrivs();					
				}
			}
		});
	}
	
	function loadBannerType()
	{
		$.ajax({type: 'GET',
				url: '/banner/listbannertype',
				async: false,
				success: function(data) {
				var jsonData = $.parseJSON(data);
				if (jsonData.code == 0)
				{
					var htmlOptions = "";
					for (var i = 0; i < jsonData.data.length; i++) {
						htmlOptions += "<option value='" + jsonData.data[i].ID + "'>" + jsonData.data[i].NAME + "</option>";
					}
						
					$("#listBannerTypeID").html(htmlOptions);
					$("#newBannerTypeID").html(htmlOptions);
					$("#editBannerTypeID").html(htmlOptions);
				}
			  }			  
		});
	}
	
	function loadBanner()
	{
		var typeID = $("#listBannerTypeID").val();
		if (typeID > 0)
		{
			$.get("/banner/list", 
				  {id: typeID, from: page * numberOfBanners, numberOfBanners: numberOfBanners},
				  function(data){
					  	var returnData = $.parseJSON(data);

						$('#listBannerTable tbody').remove();
						var bannerTableHTML = '<tbody>';
						for (var i = 0; i < returnData.data.length; i++)
						{
							bannerTableHTML += "<tr>";
							bannerTableHTML += '<td>' + returnData.data[i].ID + "</td>";
							if (returnData.data[i].MEDIA_TYPE == "image")
								bannerTableHTML += '<td><img src="' + returnData.data[i].MEDIA + '" width="20%" height="20%"/></td>';
							else
								bannerTableHTML += '<td>' + "&nbsp;" + "</td>";
							
							var url = returnData.data[i].URL;
							if(url.length > 25) {
								url = url.substring(0, 25) + '...';								
							}
							bannerTableHTML += '<td>' + '<a href="' + returnData.data[i].URL + '"' + 
								'target="' + returnData.data[i].TARGET + '">' + url + '</a>' + "</td>";
							
							bannerTableHTML += '<td>' + returnData.data[i].TARGET + "</td>";
							bannerTableHTML += '<td>' + returnData.data[i].PRIORITY + "</td>";
							bannerTableHTML += '<td>' + returnData.data[i].IS_ACTIVE + "</td>";
							
							if(updatePriv == 0 && deletePriv == 0) {
								bannerTableHTML += '<td>Không có</td>';
							} else {
								bannerTableHTML += 
								'<td>' + 
								(updatePriv ? '<a id="e' + returnData.data[i].ID + '" href="#" class="editBanner">Sửa</a>' : '') + 
								(updatePriv && deletePriv ? ' | ' : '') +
								(deletePriv ? '<a id="r' + returnData.data[i].ID + '" href="#" class="removeBanner">Xóa</a>' : '') + 
								'</td>';
							}				
							bannerTableHTML += '</tr>';
						}
						bannerTableHTML += '</tbody>';
						$('#listBannerTable').append(bannerTableHTML);
						
						// Edit banner event handler
						$(".editBanner").click(function(){
							var bannerID = $(this).attr("id").substr(1);
							editBanner(bannerID);
							return false;
						});
						// Remove banner event handler
						$(".removeBanner").click(function(){
							var bannerID = $(this).attr("id").substr(1);
							removeBanner(bannerID);
							return false;
						});
						
						// init quick tips for edit and remove links
						quickTip();
					} // end success function				
			); // end $.get function	
		}
	}
	
	
	//////////////////////////////////////// Quick tips //////////////////////////////////////
	function quickTip()
	{
		$(".editBanner").qtip({
			content: "Sửa banner",
			show: {when: {event: "mouseover"}},
			hide: {when: {event: "mouseout"}},
			style: {
				name: "cream",
				border: {
					width: 2,
					radius: 3
				}
			},
			position: {
				corner: {
					target: 'leftMiddle',
					tooltip: 'rightMiddle'
				}
			}
		});
		$(".removeBanner").qtip({
			content: "Xóa banner",
			show: {when: {event: "mouseover"}},
			hide: {when: {event: "mouseout"}},
			style: {
				name: "cream",
				border: {
					width: 2,
					radius: 3
				}
			},
			position: {
				corner: {
					target: 'leftMiddle',
					tooltip: 'rightMiddle'
				}
			}
		});
	} // end quickTip function	
	
	//////////////////////////// Event helpers /////////////////////////////
	function newBanner()
	{
		$("#newBannerErrorRow").css("display", "none");
		$("#newBannerDialog").dialog("open");
	}
	
	function editBanner(bannerID)
	{
		if (bannerID > 0)
		{
			$.get("/banner/getinfo", {id: bannerID}, function(data){
				var returnData = $.parseJSON(data);
				if (returnData.code == 0)
				{
					$("#editBannerErrorRow").css("display", "none");
					$("#editBannerTypeID").val(returnData.data.BANNER_TYPE_ID);
					$("#editBannerURL").val(returnData.data.URL);
					$("#editBannerTarget").val(returnData.data.TARGET);
					$("#editBannerPriority").val(returnData.data.PRIORITY);
					if (returnData.data.IS_ACTIVE == 1)
						$("#editBannerIsActive").attr("checked", true);
					else
						$("#editBannerIsActive").attr("checked", false);
					$("#editBannerID").val(returnData.data.ID);
					$("#editBannerOldFilename").val(returnData.data.MEDIA);
					$("#editBannerDialog").dialog("open");
				}
			});
		}
	}
	
	function removeBanner(bannerID)
	{
		if (bannerID > 0)
		{
			$("#removeShowBannerID").html(bannerID);
			$("#removeBannerID").val(bannerID);
			$("#removeBannerDialog").dialog("open");
		}
	}
	
	
	/////////////////////////////// New banner uploadify ////////////////////////////	
	$("#newBannerUpload").uploadify({
	    "swf": "/uploadify/uploadify.swf",
	    "uploader": "/uploadify/uploadify.php",
		"buttonText": "+",
	    "cancelImage": "/uploadify/uploadify-cancel.png",
	    "checkExisting": "/uploadify/uploadify-check-exists.php",
	    "auto" : true,		
		"fileTypeExts": "*.jpg;*.gif;*.png",
	  	"fileTypeDesc": "Image files",
		"height": 21,
		"width": 21,
		"removeCompleted": false,
		"onUploadSuccess": function(file, data, response){
			var fileName = file.name;
			if (fileName == '')
			{
				$("#newBannerErrorRow").css("display", "");
				$("#newBannerErrorMessage").html(fileName);
				$("#newBannerFilename").val(-1);			
			}
			else
			{
				$("#newBannerErrorRow").css("display", "none");
				$("#newBannerErrorMessage").html("");
				$("#newBannerFilename").val(fileName);
			}
	    }
	});

	
	/////////////////////////////// Edit banner uploadify ////////////////////////////	
	$("#editBannerUpload").uploadify({
	    "swf": "/uploadify/uploadify.swf",
	    "uploader": "/uploadify/uploadify.php",
		"buttonText": "+",
	    "cancelImage": "/uploadify/uploadify-cancel.png",
	    "checkExisting": "/uploadify/uploadify-check-exists.php",
	    "auto" : true,
		"fileTypeExts": "*.jpg;*.gif;*.png",
	  	"fileTypeDesc": "Image files",
		"height": 21,
		"width": 21,
		"removeCompleted": false,
		"onUploadSuccess": function(file, data, response){
			var fileName = file.name;
			if (fileName == '')
			{
				$("#editBannerErrorRow").css("display", "");
				$("#editBannerErrorMessage").html(fileName);
				$("#editBannerFilename").val(-1);			
			}
			else
			{
				$("#editBannerErrorRow").css("display", "none");
				$("#editBannerErrorMessage").html("");
				$("#editBannerFilename").val(fileName);
			}
		}
	});
	
	//////////////////////// Init functions //////////////////////////////
	function initBannerTypeSelect()
	{
		$('#listBannerTypeID').change(function(){
			loadBanner();
		});	
	}
	
	function initNewBannerDialog()
	{
		$("#newBannerDialog").dialog({
			autoOpen: false,
			width: 570,
			resizable: false,
			buttons: {
				"Thêm": function(){			
					$("#newBannerErrorRow").css("display", "none");
					$.post("/banner/add", $("#newBannerForm").serialize(), function(data){						
						var returnData = $.parseJSON(data);					
						if (returnData.code == 0)
						{		
							loadBanner();
							$('#newBannerDialog').dialog("close");					
						}
						else
						{						
							$("#newBannerErrorRow").css("display", "");
							$("#newBannerErrorMessage").html(returnData.data);
						}
					});
					return false;
				},
				"Đóng": function(){
					$(this).dialog("close");
				}
			},
			close: function(event, ui)
			{
				$("#newBannerTypeID").val("");
				$("#newBannerURL").val("");
				$("#newBannerTarget").val("");
				$("#newBannerPriority").val("");
				$("#newBannerIsActive").attr("checked", true);
				$("#newBannerFilename").val("");
			}
		});
	}
	
	function initEditBannerDialog()
	{
		$("#editBannerDialog").dialog({
			autoOpen: false,
			width: 570,
			resizable: false,
			buttons: {
				"Cập nhật": function(){
					$("#editBannerErrorRow").css("display", "none");
					$.post("/banner/edit", $("#editBannerForm").serialize(), function(data){
						var returnData = $.parseJSON(data);
						if (returnData.code == 0)
						{				
							loadBanner();
							$('#editBannerDialog').dialog("close");
						}
						else
						{
							$("#editBannerErrorRow").css("display", "");
							$("#editBannerErrorMessage").html(returnData.data);
						}
					});
					return false;
				},
				"Đóng": function(){
					$(this).dialog("close");
				}
			},
			close: function(event, ui)
			{
				$("#editBannerFilename").val("");				
			}
		});
	}
	
	function initRemoveBannerDialog()
	{
		$("#removeBannerDialog").dialog({
			autoOpen: false,
			width: 220,
			resizable: false,
			buttons: {
				"Xóa": function(){
					$.post("/banner/remove", $("#removeBannerForm").serialize(), function(data){
						var returnData = $.parseJSON(data);
						if (returnData.code == 0)
						{
							loadBanner();
							$('#removeBannerDialog').dialog("close");
						}
					});
					return false;
				},
				"Đóng": function(){
					$(this).dialog("close");
				}
			}
		});
	}
});